<template>
  <div
    class="categoryDialogContainer"
    v-if="isCategoryDialogShow"
    v-loading="isLoading"
    element-loading-text="正在加载数据中..."
  >
    <div class="categoryDialogTitle">
      <div class="title-left">
        <div class="bar"></div>
        <div class="title-text">条件查询统计</div>
      </div>
      <div class="title-right">
        <!-- <div  tabindex="0" class="icon">-</div> -->
        <div tabindex="0" class="icon" @click="closeDialog">×</div>
      </div>
    </div>
    <div class="categoryDialogContent">
      <div class="contentButton">
        <div
          class="menuButton"
          :class="{ active: isNormalShow }"
          @click="changeMenu('normal')"
        >
          条件查询
        </div>
        <div
          class="menuButton"
          :class="{ active: isAdvancedShow }"
          @click="changeMenu('advanced')"
        >
          查询模板
        </div>
      </div>
      <div
        v-if="isAdvancedShow"
        style="
          width: 463px;
          height: 30px;
          background-color: #4070a2;
          font-size: 16px;
          color: white;
          line-height: 30px;
          display: flex;
          justify-content: center;
        "
      >
        <div>条件查询统计模板</div>
      </div>
      <div v-if="isAdvancedShow" style="width: 460px; margin-top: 10px">
        <span>统计模板选择：</span>

        <select
          style="width: 20rem"
          v-model="templateConditionsId"
          @change="templateSearchById"
        >
          <option :value="item.id" v-for="(item, index) in templateGroup">
            {{ item.queryTemplateName }}
          </option>
        </select>
      </div>
      <div
        v-if="isNormalShow && isSearchShow"
        style="
          width: 100%;
          height: 30px;
          background-color: #4070a2;
          font-size: 16px;
          color: white;
          line-height: 30px;
        "
      >
        查询条件选择
      </div>
      <div
        v-if="isNormalShow && isSearchShow"
        style="display: flex; justify-content: center; width: 100%"
      >
        <div class="conditionContent" style="margin: 1rem 0; width: 100%">
          <div
            class="conditionContent-type"
            style="display: flex; margin: 0 auto; width: 100%"
          >
            <div style="display: flex; flex: 1">
              <div
                style="
                  flex: 1;
                  height: 25px;
                  line-height: 25px;
                  background-color: #fff;
                  color: black;
                  border-radius: 3px;
                  text-align: center;
                "
                class="menuArea"
                :class="{ active: isAllAreaShow }"
                @click="changeArea('all')"
              >
                全部区域
              </div>
              <!-- <div
                style="
                  height: 25px;
                  flex: 1;
                  line-height: 25px;
                  background-color: #fff;
                  color: black;
                  border-radius: 3px;
                  text-align: center;
                "
                class="menuArea"
                :class="{ active: isNowAreaShow }"
                @click="changeArea('now')"
              >
                当前区域
              </div> -->
              <div
                style="
                  flex: 1;
                  height: 25px;
                  line-height: 25px;
                  background-color: #fff;
                  color: black;
                  border-radius: 3px;
                  text-align: center;
                "
                class="menuArea"
                :class="{ active: isEnvShow }"
                @click="changeArea('env')"
              >
                自定义矩形
              </div>
              <div
                style="
                  flex: 1;
                  height: 25px;
                  line-height: 25px;
                  background-color: #fff;
                  color: black;
                  border-radius: 3px;
                  text-align: center;
                "
                class="menuArea"
                :class="{ active: isCoorShow }"
                @click="changeArea('coor')"
              >
                自定义多边形
              </div>
            </div>
          </div>
          <div
            class="conditionContent-area"
            style="
              width: 300px;
              display: flex;
              margin-top: 10px;
              margin: 0.5rem 0.5rem;
            "
          >
            <!-- :disable-branch-nodes="true" -->
            <Treeselect
              placeholder="选择查询表"
              :options="conditionQueryTableList"
              :normalizer="normalizer"
              v-model="targetQueryCondition.queryTable"
              noOptionsText="没有数据"
              noResultsText="没有搜索结果"
              @select="(node) => handleInputChange(node)"
            ></Treeselect>
          </div>
          <div
            class="conditionContent-area"
            style="width: 100%; display: flex; margin-top: 10px"
          >
            <select
              v-model="targetQueryCondition.attribute"
              @change="targetSelect"
              style="width: 25%"
            >
              <option
                v-for="item in this.conditionQueryAttributeList"
                :value="item"
              >
                {{ item.queryName }}
              </option>
            </select>

            <select v-model="targetQueryCondition.operator" style="width: 25%">
              <option
                :value="item"
                v-for="(item, index) in targetCompareOption"
              >
                {{ item.queryName }}
              </option>
            </select>

            <div style="display: flex">
              <input
                v-model="targetQueryCondition.value.queryValue"
                v-show="isValueInputShow"
                style=""
              />
              <el-date-picker
                style="width: 60%; margin: 0 0.5rem"
                v-model="targetQueryCondition.value.queryValue"
                type="datetime"
                v-show="isValueTimeShow"
                format="yyyy-MM-dd HH:mm:ss"
                value-format="yyyy-MM-dd HH:mm:ss"
              >
              </el-date-picker>
              <div
                @click="addCondition"
                style="
                  border-radius: 50%;
                  background-color: #4070a2;
                  width: 1.5rem;
                  height: 1.5rem;
                  cursor: pointer;
                "
                title="添加条件"
              >
                <img
                  style="height: 1.5rem"
                  src="../../../assets/向下箭头.png"
                  alt=""
                />
              </div>
            </div>
          </div>
        </div>
      </div>

      <div v-if="isNormalShow && isSearchShow">
        <div class="conditionSelect">
          <div class="item" v-for="(item, index) in conditionQueryGroupList">
            <div style="">
              <select
                v-if="index > 0"
                v-model="item.connector.queryValue"
                style="width: auto"
              >
                <option value="AND">且</option>
                <option value="OR">或</option></select
              ><span>{{ item.queryTableValue.queryName }}:</span
              ><span>{{ item.attribute.queryName }}</span
              ><span>{{ item.operator.queryName }}</span>
              <span>{{ item.value.queryValue }}</span>
            </div>
            <button
              style="
                width: 4rem;
                background: transparent;
                border: 1px solid #ccc;
                border-radius: 2px;
                cursor: pointer;
              "
              @click="delConditionItem(index)"
            >
              删除
            </button>
          </div>
        </div>
      </div>
      <div
        v-if="isNormalShow"
        style="
          width: 100%;
          height: 30px;
          background-color: #4070a2;
          font-size: 16px;
          color: white;
          line-height: 30px;
          margin-top: 1rem;
        "
      >
        统计结果
      </div>
      <div v-if="true" style="width: 100%; margin-top: 10px; height: 70%">
        <input
          type="text"
          style="width: 15rem; margin: 0.5rem 0"
          placeholder="关键字查询"
        />

        <el-table
          id="dataTable"
          :data="tableData"
          v-loading="tableLoading"
          @row-click="handlePointListClick"
          max-height="400"
          border
          style="width: 100%"
        >
          <el-table-column prop="keywords" label="关键字"></el-table-column>
          <el-table-column prop="cnname" label="类别"></el-table-column>
          <el-table-column prop="value" label="口径"></el-table-column>
        </el-table>

        <div class="tablePage">
          <el-pagination
            @current-change="handleCurrentChange"
            :current-page="pageinfoItem.currentPage"
            :pager-count="3"
            :page-size="pageinfoItem.pageSize"
            :total="pageinfoItem.totalItems"
            layout="total, prev, pager, next, jumper"
          >
          </el-pagination>
        </div>
      </div>
      <div v-if="isNormalShow" class="bottom-button" style="">
        <el-button
          v-if="!isSearchShow"
          style=""
          size="mini"
          icon="el-icon-search"
          @click="
            isSearchShow = !isSearchShow;
            tableData = [];
          "
          >返回</el-button
        >
        <el-button
          style=""
          size="mini"
          icon="el-icon-search"
          @click="searchConditionResult"
          v-show="isSearchShow"
          >查询结果</el-button
        >
        <el-button
          style=""
          size="mini"
          icon="el-icon-search"
          @click="showThemicTemplateData = true"
          v-show="!isSearchShow"
          v-if="roles == '管理员'"
          >保存专题图</el-button
        >
        <el-button
          size="mini"
          icon="el-icon-finished"
          @click="showSetTemplateData = true"
          >保存模板</el-button
        >
        <el-button size="mini" icon="el-icon-s-data" @click="openStatisicDialog"
          >统计</el-button
        >
        <el-button size="mini" icon="el-icon-folder-opened" @click="exportForm">
          导出
        </el-button>
      </div>

      <el-dialog
        title="管网资产统计图表"
        :modal="false"
        :visible.sync="dialogStatisicVisible"
      >
        <EChartsVue :chart-data="chartData"></EChartsVue>
      </el-dialog>

      <!-- 高级统计界面 -->

      <!-- <div v-if="isAdvancedShow" class="bottom-button" style="margin-left: 215px">
                <el-button size="mini" icon="el-icon-circle-plus-outline" @click="addArea">
                    新增
                </el-button>
            </div> -->
    </div>
    <div class="setTemplateData" v-if="showThemicTemplateData" v-drag>
      <span>请输入要保存的专题图名称：</span>
      <input type="text" v-model="themicTemplateData.name" />
      <span>请输入要保存的专题图备注：</span>
      <input type="text" v-model="themicTemplateData.note" />
      <div class="btnGroup">
        <button @click="saveThemicTemplate">保存</button>
        <button @click="showThemicTemplateData = false">取消</button>
      </div>
    </div>
    <div class="setTemplateData" v-if="showSetTemplateData" v-drag>
      <span>请输入要保存的查询模板名称：</span>
      <input type="text" v-model="templateData.name" />
      <span>请输入要保存的查询模板备注：</span>
      <input type="text" v-model="templateData.note" />
      <div class="btnGroup">
        <button @click="saveTemplate">保存</button>
        <button @click="showSetTemplateData = false">取消</button>
      </div>
    </div>
    <AddArea
      :dialogVisible="isAddAreaShow"
      :areaData="areaText"
      @update:dialogVisible="isAddAreaShow = $event"
    ></AddArea>
  </div>
</template>

<script>
import * as XLSX from "xlsx";
import { getVectorContext } from "ol/render";
import { Fill, Stroke, Style, Circle as circleStyle } from "ol/style";
import * as FileSaver from "file-saver";
import dmgis from "@/api/dmgis";
import {
  getEquipStatistics,
  deleteConditionTemplate,
  getConditionQueryList,
  saveConditonQueryTemplate,
  getConditionTemplateList,
  searchConditonQueryTemplate,
  getallListTemplate,
  getResultByTemplate,
  getChineseByEnglish,
  getConditionAttributeList,
  getStaticResultExcel,
  saveConditonQueryThemicTemplate,
} from "@/api/EquipmentManagement.js";
import AddArea from "./SpatialAddArea.vue";
import EChartsVue from "../../UtilView/ECharts.vue";
import { F } from "vue-step-wizard";
export default {
  name: "equipSpatial",
  props: {
    dialogVisible: {
      type: Boolean,
      required: true,
    },
  },
  components: {
    AddArea,
    EChartsVue,
  },
  data() {
    return {
      showThemicTemplateData: false,
      themicTemplateData: {
        name: "",
        note: "",
      },
      menuState: "normal",
      pageinfoItem: {
        totalItems: 0,
        currentPage: 1,
        pageSize: 100,
      },
      tableLoading: false,
      isValueTimeShow: false,
      isValueInputShow: true,
      templateConditionsId: "",
      templateGroup: [],
      keywords: [],
      isLoading: false,
      templateData: {
        name: "",
        note: "",
      },
      showSetTemplateData: false,
      isSearchShow: true,
      conditionQueryGroupList: [],
      targetQueryCondition: {
        queryTableValue: {
          queryName: "",
          queryValue: "",
        },
        attribute: {
          queryName: "",
          queryValue: "",
        },
        operator: {
          queryName: "",
          queryValue: "",
        },
        value: {
          queryName: "",
          queryValue: "",
        },
        connector: {
          queryName: "且",
          queryValue: "AND",
        },
      },
      conditionQueryTableList: [],
      conditionQueryAttributeList: [],
      isAddAreaShow: false,
      isNormalShow: true,
      isAdvancedShow: false,
      targetQueryTable: "",
      targetQueryAtrribute: "",
      targetOption: "",

      targetCompareOption: [
        { queryName: "大于", queryValue: ">" },
        { queryName: "小于", queryValue: "<" },
        { queryName: "等于", queryValue: "=" },
        { queryName: "大于等于", queryValue: ">=" },
        { queryName: "小于等于", queryValue: "<=" },
      ],
      map: null,
      isAllAreaShow: true,
      isNowAreaShow: false,
      isEnvShow: false,
      isCoorShow: false,
      tableData: [],
      areaTableData: [],
      tableDataResult: [],
      conditionTemplateTableData: [],
      dialogStatisicVisible: false,
      chartData: {
        xAxisData: [],
        seriesData: [],
      },
      areaData: null,
      areaText: "",
      projectLayer: null,
      areaText: "",
      inputValue: "",
      querySpatialLayer: null,
    };
  },
  computed: {
    roles() {
      return JSON.parse(localStorage.getItem("userInfo")).roles.name;
    },
    isCategoryDialogShow() {
      // 返回 prop 的值
      return this.dialogVisible;
    },
    getArea() {
      return this.$store.state.area;
    },
  },
  watch: {
    getArea(newVal) {
      this.areaData = newVal;
      this.areaText = JSON.stringify(this.areaData.getCoordinates()[0]);
      if (this.isEnvShow) {
        this.getFeatureByArea(this.areaData);
      } else if (this.isCoorShow) {
        this.getFeatureByMultiArea(this.areaData);
      }
    },
    tableData(newVal) {
      for (let i = 0; i < newVal.length; i++) {
        this.chartData.xAxisData.push(newVal[i].cnname);
        this.chartData.seriesData.push(Number(newVal[i].value));
      }
    },
  },
  methods: {
    handlePointListClick(row) {
      console.log(row);

      if (row.coordinate.length > 0) {
        this.map.marker.addMarker(
          row.coordinate[0],
          row.coordinate[1],
          this.querySpatialLayer,
          {
            scale: 1.5, //大小
            radius: 10,
            pBorderColor: "#000000",
            pBorderWidth: 2,
            pFillColor: "green",
          },
          ""
        );
        this.map.panTo(row.coordinate, 18);
      }
    },
    saveThematicMap() {
      const h = this.$createElement;
      this.$msgbox({
        title: "",
        message: h("p", null, [h("span", null, "是否将数据保存为专题图？ ")]),
        showCancelButton: true,
        distinguishCancelAndClose: true,
        confirmButtonText: "确定",
        cancelButtonText: "取消",
      }).then((action) => {
        if (action == "confirm") {
        }
      });
    },
    handleCurrentChange(page) {
      this.pageinfoItem.currentPage = page;
      this.tableData = [];
      if (this.menuState == "normal") {
        let queryParams = this.conditionQueryGroupList.map((item, index) => {
          if (index == 0) {
            item.connector.queryValue = "";
          }
          return {
            tableName: item.queryTableValue.queryValue,
            attribute: item.attribute.queryValue,
            operator: item.operator.queryValue,
            value: item.value.queryValue,
            connector: item.connector.queryValue,
          };
        });
        let params = {
          conditions: queryParams,
          keywordsList: this.keywords,
          pageNum: this.pageinfoItem.currentPage,
          pageSize: 100,
        };
        this.tableLoading = true;
        searchConditonQueryTemplate(params)
          .then((res) => {
            if (res.code == 200) {
              // this.$message.success("查询成功");
              this.tableData = res.data.map((item) => {
                let keywords = item.keywords?.trim().split(" ") || [];
                let cnname =
                  (item.pipeDiameter || item.nodeProperty || item.style)
                    ?.trim()
                    .split(" ") || [];
                let value =
                  item.diameter?.trim().split(" ") ||
                  item.pipeDiameter?.trim().split(" ") ||
                  [];
                let coordinate = [];

                if (item.xcoordinate && item.ycoordinate) {
                  coordinate = [
                    item.xcoordinate.replace(/\s+/g, ""),
                    item.ycoordinate.replace(/\s+/g, ""),
                  ];
                }

                return {
                  keywords: keywords,
                  cnname: cnname,
                  value: value,
                  coordinate: coordinate,
                };
              });
              this.tableLoading = false;
              this.pageinfoItem.totalItems = res.total;

              // res.data.forEach((item) => {
              //   this.map.marker.addMarker(
              //     Number(item.x),
              //     Number(item.y),
              //     this.querySpatialLayer,
              //     {
              //       scale: 1.5, //大小
              //       radius: 5,
              //       pBorderColor: "#000000",
              //       pBorderWidth: 1,
              //       pFillColor: "green",
              //     },
              //     item
              //   );
              // });
            }
          })
          .catch((err) => {
            this.tableLoading = false;
          });
      } else {
        let params = this.templateConditionsId;
        this.tableLoading = true;
        getResultByTemplate({
          templateId: params,
          pageNum: this.pageinfoItem.currentPage,
          pageSize: 100,
        }).then((res) => {
          this.tableData = res.data.map((item) => {
            let keywords = item.keywords?.trim().split(" ") || [];
            let cnname =
              (item.pipeDiameter || item.nodeProperty || item.style)
                ?.trim()
                .split(" ") || [];
            let value =
              item.diameter?.trim().split(" ") ||
              item.pipeDiameter?.trim().split(" ") ||
              [];

            return { keywords, cnname, value };
          });
          this.tableLoading = false;
          // res.data.forEach((item) => {
          //   this.map.marker.addMarker(
          //     Number(item.x),
          //     Number(item.y),
          //     this.querySpatialLayer,
          //     {
          //       scale: 1.5, //大小
          //       radius: 5,
          //       pBorderColor: "#000000",
          //       pBorderWidth: 1,
          //       pFillColor: "green",
          //     },
          //     item
          //   );
          // });
        });
      }
    },
    handleInputChange(newValue) {
      this.conditionQueryGroupList = [];
      this.targetQueryCondition.value.queryValue = "";
      this.targetQueryCondition.queryTableValue = {
        queryName: newValue.label,
        queryValue: newValue.value,
      };
      this.targetQueryCondition.attribute = "";
      this.conditionQueryAttributeList = [];
      this.targetCompareOption = [];
      getConditionAttributeList({ id: newValue.id }).then((res) => {
        this.conditionQueryAttributeList = res.data.map((item) => {
          return {
            queryName: item.attributeName,
            queryValue: item.attributeValue,
            options: item.options,
          };
        });
      });
    },
    normalizer(node) {
      return {
        id: node.id,
        label: node.label,
        value: node.value,
        children: node.children && node.children.length > 0 ? node.children : 0,
      };
    },
    templateSearchById() {
      this.pageinfoItem = {
        totalItems: 0,
        currentPage: 1,
        pageSize: 100,
      };
      let params = this.templateConditionsId;
      this.tableLoading = true;
      getResultByTemplate({
        templateId: params,
        pageNum: this.pageinfoItem.currentPage,
        pageSize: 100,
      })
        .then((res) => {
          this.$message.success("查询成功");
          this.tableData = res.data.map((item) => {
            let keywords = item.keywords?.trim().split(" ") || [];
            let cnname =
              (item.pipeDiameter || item.nodeProperty || item.style)
                ?.trim()
                .split(" ") || [];
            let value =
              item.diameter?.trim().split(" ") ||
              item.pipeDiameter?.trim().split(" ") ||
              [];

            return { keywords, cnname, value };
          });
          this.tableLoading = false;
          this.pageinfoItem.totalItems = res.total;
        })
        .catch((err) => {
          this.tableLoading = false;
        });
    },
    searchConditionResult() {
      if (this.conditionQueryGroupList.length == 0) {
        this.$message.warning("请先添加查询条件");
        return;
      }
      this.pageinfoItem = {
        totalItems: 0,
        currentPage: 1,
        pageSize: 100,
      };
      this.querySpatialLayer.getSource().clear();
      this.isSearchShow = false;

      let queryParams = this.conditionQueryGroupList.map((item, index) => {
        if (index == 0) {
          item.connector.queryValue = "";
        }
        return {
          tableName: item.queryTableValue.queryValue,
          attribute: item.attribute.queryValue,
          operator: item.operator.queryValue,
          value: item.value.queryValue,
          connector: item.connector.queryValue,
        };
      });
      let params = {
        conditions: queryParams,
        keywordsList: this.keywords,
        pageNum: this.pageinfoItem.currentPage,
        pageSize: 100,
      };
      this.tableLoading = true;
      searchConditonQueryTemplate(params)
        .then((res) => {
          if (res.code == 200) {
            this.$message.success("查询成功");

            this.tableData = res.data.map((item) => {
              let keywords = item.keywords?.trim().split(" ") || [];
              let cnname =
                (item.material || item.nodeProperty || item.style)
                  ?.trim()
                  .split(" ") || [];
              let value =
                item.diameter?.trim().split(" ") ||
                item.pipeDiameter?.trim().split(" ") ||
                [];
              let coordinate = [];
              if (item.xcoordinate && item.ycoordinate) {
                coordinate = [
                  item.xcoordinate.replace(/\s+/g, ""),
                  item.ycoordinate.replace(/\s+/g, ""),
                ];
              }
              return {
                keywords: keywords,
                cnname: cnname,
                value: value,
                coordinate: coordinate,
              };
            });
            this.tableLoading = false;
            this.pageinfoItem.totalItems = res.total;
          }
        })
        .catch((err) => {
          this.tableLoading = false;
        });
    },
    delConditionItem(index) {
      this.conditionQueryGroupList.splice(index, 1);
    },
    addCondition() {
      if (
        this.targetQueryCondition.queryTableValue.queryName == "" ||
        this.targetQueryCondition.attribute.queryName == "" ||
        !this.targetQueryCondition.operator
      ) {
        this.$message.warning("请选择查询条件");
        return;
      }
      let newCondition = JSON.parse(JSON.stringify(this.targetQueryCondition));
      this.conditionQueryGroupList.push(newCondition);

      //   this.conditionQueryGroupList.push({
      //     queryTableValue: this.targetQueryTable,
      //     attribute: this.targetQueryAtrribute,
      //     operator: this.targetOption,
      //     value: this.inputValue,
      //     connector: "AND",
      //   });
    },
    openStatisicDialog() {
      this.dialogStatisicVisible = true;
    },
    initMap() {
      setTimeout(() => {
        this.map = this.$store.getters.Map;
        if (this.map) {
        } else {
          console.error("地图实例未找到");
        }
        this.projectLayer = this.$store.getters.projectLayer;
        this.querySpatialLayer =
          this.map.layer.createVectorLayer("空间查询点图层");
      }, 1000); // 延迟 1000 毫秒（1秒）后执行
    },

    async changeMenu(val) {
      this.menuState = val;
      this.pageinfoItem = {
        totalItems: 0,
        currentPage: 1,
        pageSize: 100,
      };
      if (val == "normal") {
        this.tableData = [];
        this.isNormalShow = true;
        this.isAdvancedShow = false;
        this.isSearchShow = true;
      } else {
        (this.targetQueryCondition.attribute = {
          queryName: "",
          queryValue: "",
        }),
          (this.conditionQueryAttributeList = []);
        this.targetQueryCondition.operator = {
          queryName: "",
          queryValue: "",
        };
        this.tableData = [];
        this.isNormalShow = false;
        this.isAdvancedShow = true;
        await getallListTemplate().then((res) => {
          this.templateGroup = res.data.map((item) => {
            return {
              queryTemplateName: item.queryTemplateName,
              id: item.id,
            };
          });
        });
      }
    },
    changeArea(val) {
      this.map.interaction.cancelYjDraw();
      this.querySpatialLayer.getSource().clear();
      this.areaTableData = [];
      this.keywords = [];
      this.map.map.un("dblclick", this.getFeatureByArea);
      this.map.map.un("dblclick", this.getFeatureByMultiArea);
      switch (val) {
        case "all":
          this.map.interaction.cancelYjDraw();
          this.isAllAreaShow = true;
          this.isNowAreaShow = false;
          this.isEnvShow = false;
          this.isCoorShow = false;
          break;
        case "now":
          this.map.interaction.cancelYjDraw();
          this.isAllAreaShow = false;
          this.isNowAreaShow = true;
          this.isEnvShow = false;
          this.isCoorShow = false;
          break;

        case "env":
          this.map.interaction.addNewAreaDraw("Rectangle", 1);
          this.addEnvArea();
          this.isAllAreaShow = false;
          this.isNowAreaShow = false;
          this.isEnvShow = true;
          this.isCoorShow = false;
          break;
        case "coor":
          this.map.interaction.addNewAreaDraw("Polygon", 1);
          this.addCoorArea();
          this.isAllAreaShow = false;
          this.isNowAreaShow = false;
          this.isEnvShow = false;
          this.isCoorShow = true;
          break;
      }
    },
    exportForm() {
      if (this.tableData.length === 0) {
        this.$message.warning("暂无可导出的数据!");
        return;
      }
      let queryParams = this.conditionQueryGroupList.map((item, index) => {
        if (index == 0) {
          item.connector.queryValue = "";
        }
        return {
          tableName: item.queryTableValue.queryValue,
          attribute: item.attribute.queryValue,
          operator: item.operator.queryValue,
          value: item.value.queryValue,
          connector: item.connector.queryValue,
        };
      });
      let params = {
        conditions: queryParams,
        keywordsList: this.keywords,
      };
      getStaticResultExcel(params).then((res) => {
        const blob = new Blob([res.data], {
          type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
        });
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement("a");
        a.href = url;
        a.download = "数据表格.xlsx";
        document.body.appendChild(a);
        a.click();
        window.URL.revokeObjectURL(url);
        document.body.removeChild(a);
      });
      // let tables = document.getElementById("dataTable").cloneNode(true);
      // let table_book = XLSX.utils.table_to_book(tables);
      // let table_write = XLSX.write(table_book, {
      //   bookType: "xlsx",
      //   bookSST: true,
      //   type: "array",
      // });
      // try {
      //   FileSaver.saveAs(
      //     new Blob([table_write], { type: "application/octet-stream" }),
      //     `空间查询统计表.xlsx`
      //   );
      // } catch (e) {
      //   if (typeof console !== "undefined") ;
      // }
    },
    closeDialog() {
      // 通过修改 prop 来关闭弹窗
      this.$emit("update:dialogVisible", false);
    },
    targetSelect() {
      this.targetQueryCondition.operator = { queryName: "", queryValue: "" };
      this.targetQueryCondition.value.queryValue = "";
      this.targetCompareOption =
        this.targetQueryCondition.attribute.options.map((item) => {
          if (
            this.targetQueryCondition.attribute.queryName.includes("时间") ||
            this.targetQueryCondition.attribute.queryName.includes("日期")
          ) {
            this.isValueInputShow = false;
            this.isValueTimeShow = true;
          } else if (item.visible == "true") {
            this.isValueInputShow = true;
            this.isValueTimeShow = false;
          } else {
            this.isValueInputShow = false;
            this.isValueTimeShow = false;
          }
          return {
            queryName: item.label,
            queryValue: item.value,
          };
        });
    },
    handleDelete(index, row) {
      // 这里编写删除行的逻辑
      // 例如，从 tableData 中移除该行
      deleteConditionTemplate({ id: row.id }).then((res) => {
        if (res.code == 200) {
          this.$message({
            showClose: true,
            message: res.message,
            type: "success",
          });
          for (let i = 0; i < this.conditionTemplateTableData.length; i++) {
            if (this.conditionTemplateTableData[i].id == row.id) {
              this.conditionTemplateTableData.splice(i, 1);
            }
          }
        }
      });
    },
    // 新增区域按钮点击事件
    addArea() {
      this.map.interaction.addNewAreaDraw("Polygon", 1);
      this.map.map.on("dblclick", (event) => {
        // 你的处理逻辑
        this.isAddAreaShow = true;
        // 可以在这里执行你想要进行的操作，比如完成绘制等
      });
    },
    //自定义矩形区域点击按钮
    addEnvArea() {
      this.areaData = null;
      this.areaText = "";

      // this.map.map.on("dblclick", this.getFeatureByArea);
    },
    getFeatureByArea() {
      this.map.map.un("dblclick", this.getFeatureByArea);
      if (this.areaData) {
        this.isLoading = true;
        //调用dmgis服务
        let resultData = [];

        let areaRect = this.areaData.getCoordinates()[0];
        let getFeatureParams = new dmgis.object.FeatureServiceParam(
          "TapWaterMap"
        );
        let SpatialQuery = new dmgis.object.SpatialQuery();
        let rect = new dmgis.object.Envelope(); //矩形范围
        rect.minx = areaRect[0][0];
        rect.miny = areaRect[0][1];
        rect.maxx = areaRect[2][0];
        rect.maxy = areaRect[2][1];
        SpatialQuery.env = rect; //矩形
        getFeatureParams.sql = SpatialQuery;
        let layersAttribute = this.$store.state.layersAttribute;
        if (layersAttribute.length == 0) {
          this.$message.warning("请先获取服务图层");
          this.isLoading = false;
          return;
        }

        let requestNum = 0;
        requestNum = this.$store.state.layersAttribute.length;
        async function getFeatureByAreaSon() {
          for (let item of layersAttribute) {
            getFeatureParams.strlayername = item;
            try {
              await this.projectLayer
                .SendFeatureMapService(getFeatureParams)
                .then((res) => {
                  if (res.objset) {
                    let dataObjectgroup = [];
                    res.objset.map((item) => {
                      let dataObject = {};
                      item.rec.forEach((data) => {
                        dataObject[data.fldname] = data.fldval;
                      });
                      dataObjectgroup.push(dataObject);
                    });
                    resultData.push({
                      layername: getFeatureParams.strlayername,
                      data: dataObjectgroup,
                    });
                  }
                  // dmgis.olmap.ServiceLayer.prototype.HandleFeatureInfo =
                  //   function (feature) {
                  //     if (feature.objset) {
                  //       let dataObjectgroup = [];
                  //       feature.objset.map((item) => {
                  //         let dataObject = {};
                  //         item.rec.forEach((data) => {
                  //           dataObject[data.fldname] = data.fldval;
                  //         });
                  //         dataObjectgroup.push(dataObject);
                  //       });
                  //       resultData.push({
                  //         layername: getFeatureParams.strlayername,
                  //         data: dataObjectgroup,
                  //       });
                  //     }
                  //   };
                });
            } catch (error) {
              console.error("获取图层特征时出错:", error);
            } finally {
              requestNum--;
              if (requestNum == 0) {
                this.$message.success("数据获取成功");
                this.isLoading = false;
                let engGroup = [];
                let chnGroup = [];
                //英取汉
                resultData.forEach((item) => {
                  // let parts = item.layername.split("_");
                  // let result = parts.slice(0, 2).join("_");
                  // item.layername = result;
                  engGroup.push(item.layername);
                });
                //汉取英
                await getChineseByEnglish(engGroup).then((res) => {
                  chnGroup = res.data;
                });
                this.keywords = [];
                console.log(resultData, "resultData");

                this.areaTableData = resultData.map((item) => {
                  item.data.forEach((data) => {
                    this.keywords.push(data.keywords);
                  });
                  let dataName = chnGroup[item.layername];
                  return {
                    cnname: dataName,
                    equipmentNum: item.data.length,
                  };
                });
              }
            }
          }
        }
        getFeatureByAreaSon.call(this);
      }
    },
    // 新增自定义多边形按钮点击事件
    addCoorArea() {
      this.areaData = null;
      this.areaText = "";

      // this.map.map.on("dblclick", this.getFeatureByMultiArea);
    },
    getFeatureByMultiArea() {
      this.map.map.un("dblclick", this.getFeatureByArea);
      if (this.areaData) {
        this.isLoading = true;
        //调用dmgis服务
        let resultData = [];
        let getFeatureParams = new dmgis.object.FeatureServiceParam(
          "TapWaterMap"
        );
        let SpatialQuery = new dmgis.object.SpatialQuery();
        let areaPos = "";
        this.areaData.getCoordinates()[0].forEach((item, index) => {
          let itemGroup = item.join(" ");
          if (index == this.areaData.getCoordinates()[0].length - 1) {
            areaPos += itemGroup;
          } else {
            areaPos += itemGroup + ";";
          }
        });
        SpatialQuery.strPos = areaPos;
        getFeatureParams.sql = SpatialQuery;
        let layersAttribute = this.$store.state.layersAttribute;
        if (layersAttribute.length == 0) {
          this.$message.warning("请先获取服务图层");
          this.isLoading = false;
          return;
        }
        let requestNum = 0;
        requestNum = this.$store.state.layersAttribute.length;

        async function getFeatureByAreaSon() {
          for (let item of layersAttribute) {
            getFeatureParams.strlayername = item;
            try {
              await this.projectLayer
                .SendFeatureMapService(getFeatureParams)
                .then((res) => {
                  if (res.objset) {
                    let dataObjectgroup = [];
                    res.objset.map((item) => {
                      let dataObject = {};
                      item.rec.forEach((data) => {
                        dataObject[data.fldname] = data.fldval;
                      });
                      dataObjectgroup.push(dataObject);
                    });
                    resultData.push({
                      layername: getFeatureParams.strlayername,
                      data: dataObjectgroup,
                    });
                  }
                  // dmgis.olmap.ServiceLayer.prototype.HandleFeatureInfo =
                  //   function (feature) {
                  //     if (feature.objset) {
                  //       let dataObjectgroup = [];
                  //       feature.objset.map((item) => {
                  //         let dataObject = {};
                  //         item.rec.forEach((data) => {
                  //           dataObject[data.fldname] = data.fldval;
                  //         });
                  //         dataObjectgroup.push(dataObject);
                  //       });
                  //       resultData.push({
                  //         layername: getFeatureParams.strlayername,
                  //         data: dataObjectgroup,
                  //       });
                  //     }
                  //   };
                });
            } catch (error) {
              console.error("获取图层特征时出错:", error);
            } finally {
              requestNum--;
              if (requestNum == 0) {
                this.$message.success("数据获取成功");
                this.isLoading = false;
                let engGroup = [];
                let chnGroup = [];
                //英取汉
                resultData.forEach((item) => {
                  // let parts = item.layername.split("_");
                  // let result = parts.slice(0, 2).join("_");
                  // item.layername = result;
                  engGroup.push(item.layername);
                });
                //汉取英
                await getChineseByEnglish(engGroup).then((res) => {
                  chnGroup = res.data;
                });
                this.keywords = [];
                this.areaTableData = resultData.map((item) => {
                  item.data.forEach((data) => {
                    this.keywords.push(data.keywords);
                  });
                  let dataName = chnGroup[item.layername];
                  return {
                    cnname: dataName,
                    equipmentNum: item.data.length,
                  };
                });
              }
            }
          }
        }
        getFeatureByAreaSon.call(this);
      }
      // this.map.interaction.cancelYjDraw();
      this.addCoorArea();
      // const h = this.$createElement;
      // this.$msgbox({
      //   title: "多边形空间查询",
      //   message: h("p", null, [h("span", null, "是否查询该区域? ")]),
      //   showCancelButton: true,
      //   distinguishCancelAndClose: true,
      //   confirmButtonText: "确定",
      //   cancelButtonText: "取消",
      // })
      //   .then((action) => {
      //     if (action == "confirm") {

      //     }
      //   })
      //   .catch(() => {

      //   });
    },
    // targetQueryTableChange() {
    //   ;
    //   this.conditionQueryGroupList = [];
    //   for (let i = 0; i < this.conditionQueryTableList.length; i++) {
    //     if (
    //       this.targetQueryCondition.queryTableValue.queryValue ==
    //       this.conditionQueryTableList[i].queryValue
    //     ) {
    //       this.conditionQueryAttributeList =
    //         this.conditionQueryTableList[i].sonlist;
    //     }
    //   }
    // },
    saveThemicTemplate() {
      if (this.conditionQueryGroupList.length == 0) {
        this.$message.warning("请先添加查询条件");
        return;
      }
      this.showSetTemplateData = false;
      let params = {
        conditions: [],
        featureTemplateName: this.themicTemplateData.name,
        featureTemplateRemark: this.themicTemplateData.note,
        range: this.areaText,
      };
      params.conditions = this.conditionQueryGroupList.map((item, index) => {
        if (index == 0) {
          item.connector.queryValue = "";
        }
        return {
          tableName: item.queryTableValue.queryValue,
          attribute: item.attribute.queryValue,
          operator: item.operator.queryValue,
          value: Number(item.value.queryValue),
          connector: item.connector.queryValue,
        };
      });
      saveConditonQueryThemicTemplate(params).then((res) => {
        if (res.code == 200) {
          this.$message({
            message: res.message,
            type: "success",
          });
        }
      });
    },
    saveTemplate() {
      if (this.conditionQueryGroupList.length == 0) {
        this.$message.warning("请先添加查询条件");
        return;
      }
      this.showSetTemplateData = false;
      // ;
      let queryParams = this.conditionQueryGroupList.map((item, index) => {
        if (index == 0) {
          item.connector.queryValue = "";
        }
        return {
          tableName: item.queryTableValue.queryValue,
          attribute: item.attribute.queryValue,
          operator: item.operator.queryValue,
          value: item.value.queryValue,
          connector: item.connector.queryValue,
        };
      });
      let params = {
        conditions: queryParams,
        templateName: this.templateData.name,
        templateRemark: this.templateData.note,
        keywordsList: this.keywords,
      };
      console.log(this.conditionQueryGroupList, "this.conditionQueryGroupList");

      saveConditonQueryTemplate(params).then((res) => {
        if (res.code == 200) {
          this.$message({
            message: res.message,
            type: "success",
          });
        }
      });
    },
  },
  beforeDestroy() {
    if (this.map) {
      this.map.interaction.cancelYjDraw();
      this.map.map.removeLayer(this.querySpatialLayer);
      this.map.map.un("dblclick", this.getFeatureByArea);
      this.map.map.un("dblclick", this.getFeatureByMultiArea);
    }
  },
  mounted() {
    this.initMap();
    getConditionQueryList().then((res) => {
      this.conditionQueryTableList = res.data;
    });
    getConditionTemplateList().then((res) => {
      this.conditionTemplateTableData = res.data;
    });
  },
};
</script>

<style lang="scss" scoped>
::v-deep .vue-treeselect {
  color: #000;
  .vue-treeselect__single-value {
    top: -2px;
  }
  .vue-treeselect__control {
    height: 1.8rem;
    font-size: 1rem;
    line-height: 1.8rem;
    border-radius: 3px;
  }
  .vue-treeselect__placeholder {
    top: -2px;
  }
}
.setTemplateData {
  position: absolute;
  bottom: 0vh;
  left: -15vw;
  display: flex;
  flex-direction: column;
  color: #000;
  background: #fff;
  height: 15vh;
  // padding: 2rem;
  border: 1px solid;
  input {
    width: 15rem;
  }
  button {
    width: 4rem;
    height: 1.5rem;
    margin: 0.5rem;
  }
}
select {
  width: 7.5rem;
  height: 1.5rem;
  border: 1px solid #ccc;
  border-radius: 4px;
  outline: none;
  margin: 0 0.5rem;
}
input {
  width: 7.5rem;
  height: 1.2rem;
  border: 1px solid #ccc;
  border-radius: 4px;
  outline: none;
  margin: 0 0.5rem;
}
.conditionSelect {
  width: 100%;
  height: 8rem;
  background-color: #fff;
  overflow-y: scroll;
  .item {
    color: #000;
    text-align: left;
    display: flex;
    justify-content: space-between;
  }
}
::v-deep .el-checkbox {
  color: white;
}
::v-deep .el-input__inner {
  height: 26px;
}
::v-deep.el-button--primary {
  height: 1rem;
  width: 1rem;
}
.categoryDialogContainer {
  width: 25vw;
  color: white;
  position: absolute;
  top: 5vh;
  right: -18vw;
  // height: 75vh;
  z-index: 2;
  .categoryDialogTitle {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10px;
    font-size: 1rem;
    background-color: #285383;
    .title-left,
    .title-right {
      display: flex;
      align-items: center;
    }
    .bar {
      width: 5px; /* 小竖条的宽度 */
      height: 20px; /* 小竖条的高度 */
      background-color: white; /* 小竖条的颜色 */
      margin-right: 10px; /* 小竖条和文字之间的间距 */
    }
    .icon {
      width: 20px; /* 小方框的宽度 */
      height: 20px; /* 小方框的高度 */
      // border: 1px solid #4998f2; /* 小方框的边框 */
      margin-left: 5px; /* 小方框之间的间距 */
    }
    .icon:hover {
      color: #4998f2;
    }
    .icon:focus {
      color: #4998f2;
    }
  }
  .categoryDialogContent {
    padding: 10px;
    display: flex;
    flex-direction: column;
    background-color: #285383;
    font-size: 0.8rem;
    max-height: 90%;
    .contentButton {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 10px; /* 与下半部分内容的间距 */
      .menuButton {
        cursor: pointer;
        width: 50%;
        text-align: center;
      }
      .menuButton.active {
        // color: rgb(8, 46, 82);
        border-bottom: 2px solid white;
      }
    }
    .menuArea {
      cursor: pointer;
      margin: 0 2px;
    }
    .menuArea.active {
      background-color: #c4c6c8 !important;
    }
    .contentBox {
      width: 100%;
      padding: 10px;
      box-sizing: border-box;
      .formRow {
        display: flex;
        align-items: center;
        margin-bottom: 10px;

        .search_input {
          width: 100%;
          display: flex;
          align-items: center;
          justify-content: center;
          input {
            width: 80%;
          }
        }
      }
      .label {
        width: 100px;
        margin-right: 10px;
      }

      select,
      textarea,
      button {
        width: 100%;
        color: white !important;
        background-color: #4070a2;
        border: none; /* 去除边框 */
        outline: none; /* 去除焦点时的轮廓线 */
        font-size: 0.8rem;
        height: 1.5rem;
      }

      button {
        margin-right: 10px; /* 按钮之间的间距 */
      }
      button:hover {
        background-color: #4998f2;
      }
      button:focus {
        background-color: #4998f2;
      }
      textarea {
        height: 5rem;
      }

      /* 最后一行的按钮不需要 label，可以单独设置样式 */
      .formRow:last-child {
        justify-content: flex-end;
      }

      .formRow:last-child .button {
        margin-left: 10px; /* 按钮之间的间距，而不是右边距 */
      }
    }
  }
}
::v-deep .el-input {
  .el-input__inner {
    height: 1.5rem;
  }
  .el-input__icon {
    line-height: 1.5rem;
  }
}
.tablePage {
  width: 100%;
  height: 10%;
  display: flex;
  justify-content: center;
  ::v-deep .el-pagination {
    button {
      color: #fff;
      background: transparent;
      border: 1px solid #ccc !important;
      border-radius: 5px;
    }
    .el-pagination__jump {
      color: #fff;
      background: transparent;
    }
    .el-input__inner {
      background: transparent;
      color: #fff;
    }
  }
  ::v-deep .el-pagination__total {
    color: #fff;
  }
  ::v-deep .el-pager {
    color: #fff;
    .number {
      margin: 0 0.3vw;
      background: transparent;
      border: 1px solid #ccc !important;
      border-radius: 5px;
    }

    .btn-quickprev {
      background: transparent;
      border: 1px solid #ccc !important;
      border-radius: 5px;
      color: #fff;
    }
    .btn-quicknext {
      background: transparent;
      border: 1px solid #ccc !important;
      border-radius: 5px;
      color: #fff;
    }
  }
}
.bottom-button {
  display: flex;
  justify-content: center;
}
</style>
